Search a 2D Matrix
Question
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
- Integers in each row are sorted from left to right.
- The first integer of each row is greater than the last integer of the previous row.
For example,
Consider the following matrix:
|
|
Given target = 3
, return true
.
Analysis
Don’t treat it as a 2D matrix, just treat it as a sorted list
Code
|
|
Search a 2D Matrix II
Question
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
- Integers in each row are sorted in ascending from left to right.
- Integers in each column are sorted in ascending from top to bottom.
For example,
Consider the following matrix:
|
|
Given target = 5
, return true
.
Given target = 20
, return false
.
Analysis
从右上角的元素开始扫描,若当前元素小于target,说明整行元素都小于target,向下移动col;若大于target,则向左移动row,无嵌套循环
Code
|
|